/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[TokenValidateServlet.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package session;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防止表单重复提交, 验证Token的Servlet
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(name = "TokenValidateServlet", urlPatterns = "/tokenValidate")
public class TokenValidateServlet extends HttpServlet {

	private static final long serialVersionUID = -1830062602150494272L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean valid = TokenGenerator.getInstance().isTokenValid(request);
		// 如果Token有效, 将Token从Session中清楚
		if (valid) {
			TokenGenerator.getInstance().clearToken(request);
		} else {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println("重复提交");
			return;
		}

		String name = request.getParameter("username");
		System.out.println(name);

		response.sendRedirect(request.getContextPath() + "/jsp/session/success.jsp");
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}
